#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

typedef struct msgbuf {
    long mtype;
    char mtext[100];
} msg_t;


int main(int argc, const char *argv[]) {
    key_t key;
    int flag = 0;
    ssize_t n;

    key = ftok("/", 10);
    int msqid;
    msqid = msgget(key, IPC_CREAT | IPC_EXCL | 0664);
    if(msqid == -1) {
        if(errno == EEXIST) {
            msqid = msgget(key, 0664);
            printf("队列已经创建\n");
            flag = 1;
        } else {
            perror("队列创建失败\n");
            _exit(1);
        }
    } else {
        printf("队列创建成功\n");
    }

    msg_t mymsg;
    mymsg.mtype = 100;

    while(1) {
        if(flag == 0) {
            scanf("%s", mymsg.mtext);
            msgsnd(msqid, &mymsg, sizeof(mymsg.mtext) + 1, 0);
        } else {
            n = msgrcv(msqid, &mymsg, sizeof(msg_t) - sizeof(long), 100, 0);
            printf("接收到的数据[%d]：%s\n", n, mymsg.mtext);
        }
        if(strncmp(mymsg.mtext, "quit", 4)  == 0) {
            break;
        }
    }

    msgctl(msqid, IPC_RMID, NULL);

    return 0;
}
